/**
 * 
 */
package travibot.core;

import org.apache.log4j.Logger;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import travibot.engine.PositionFactory;
import travibot.model.Position;
import travibot.model.Village;

/**
 * @author macekpet
 * 
 */
public class VillagePageParser extends GenericParser implements VillageParser {

    private static Logger log = Logger.getLogger(VillagePageParser.class);

    private Village village;

    private PositionFactory positionFactory;

    public Village getVillage(Village village) {

        this.village = village;
        parseRecursive(super.getDocument());
        return this.village;
    }

    public Village getVillage() {

        if (village == null) {
            village = new Village(1);
            parseRecursive(super.getDocument());
        }
        return village;
    }

    private void parseRecursive(Node node) {

        String nodeName = node.getNodeName().toLowerCase();

        // lets parse the buildings
        if (nodeName.equals("map")) {
            NamedNodeMap attributes = node.getAttributes();
            Node name = attributes.getNamedItem("name");
            if ("map1".equals(name.getNodeValue())) {
                parseBuildings(node);
            }
        }

        Node child = node.getFirstChild();
        while (child != null) {

            parseRecursive(child);
            child = child.getNextSibling();
        }
    }

    private void parseBuildings(Node node) {

        log.info("Starting to parse positions on map");

        NodeList fields = node.getChildNodes();

        for (int i = 0; i < fields.getLength(); i++) {

            Node item = fields.item(i);
            NamedNodeMap attributes = item.getAttributes();
            if (attributes != null) {
                Node title = attributes.getNamedItem("title");
                Node href = attributes.getNamedItem("href");
                Position pos = positionFactory.getPosition(href.getNodeValue(),
                                                           title.getNodeValue(),
                                                           Position.Type.VILLAGE_SITE);
                if (pos != null)
                    village.addPosition(pos);
            }
        }
    }

    public void setPositionFactory(PositionFactory positionFactory) {

        this.positionFactory = positionFactory;
    }

}
